package com.atguigu.queue;

import java.util.Scanner;

public class ArrayQueueDemo {
    public static void main(String[] args) {
        System.out.println("队列测试开始");
        Scanner scanner = new Scanner(System.in);
        char key=' ';
        boolean isExist=false;

        ArrayQueue queue = new ArrayQueue(3);

        while(!isExist){
            System.out.println("s(show),展示全部");
            System.out.println("a(add),增加元素");
            System.out.println("g(get),获取元素");
            System.out.println("h(head),展示头部");
            System.out.println("e(exit),结束");
            key = scanner.next().charAt(0);

            switch (key){
                case 's':
                    queue.printAll();
                    break;
                case 'a':
                    System.out.println("请输入一个元素:");
                    int nextInt = scanner.nextInt();
                    queue.addElement(nextInt);
                    break;
                case 'g':
                    try {
                        int element = queue.getElement();
                        System.out.printf("获取元素%d\n",element);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'h':
                    try {
                        int headElement = queue.headElement();
                        System.out.printf("头部元素:%d\n",headElement);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'e':
                    isExist=true;
                    scanner.close();
                    break;
                default:break;
            }
        }
        System.out.println("程序结束!");
    }
}


class ArrayQueue{
    private final int maxSize;
    private int front;
    private int rear;
    private final int[] arr;

    public ArrayQueue(int arrMaxSize){
        this.maxSize=arrMaxSize;
        this.front=-1;
        this.rear=-1;
        this.arr=new int[arrMaxSize];
    }

    public boolean isFull(){
        return rear==this.maxSize-1;
    }

    public boolean isEmpty(){
        return rear==front;
    }

    public void addElement(int ele){
        if (isFull()) {
            System.out.println("队列已满,无法添加元素");
            return;
        }
        rear++;
        arr[rear]=ele;
    }

    public int getElement(){
        if (isEmpty()) {
            throw new RuntimeException("队列已空,无法获取元素");
        }

        front++;
        return arr[front];
    }

    public int headElement(){
        if (isEmpty()) {
            throw new RuntimeException("队列已空,无法获取元素");
        }

        return arr[front+1];
    }

    public void printAll(){
        if (isEmpty()) {
            System.out.println("队列为空, 无法打印");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("arr[%d]=%d\n",i,arr[i]);
        }
    }


}